package com.example.emos.wx.config.shiro;

import ch.qos.logback.core.joran.spi.HttpUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import io.swagger.annotations.Scope;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax .servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Scope(name = "prototype", description = "")//多例，每次请求都创建一个对象，不然只有一个
public class OAuth2Filter extends AuthenticatingFilter {
    @Autowired
    private ThreadLocalToken threadLocalToken ;

    @Value("${emos.jwt.cache-expire}")

    private int cacheExpire;

    @Autowired
    private JwtUtil jwtUtil;//做令牌校验

    @Autowired
    private RedisTemplate redisTemplate;
    private String getRequestToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) request;
        resp.setContentType("test/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));//允许跨域
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        threadLocalToken.clear();//清除线程中的token,因为每次请求都要清空线程中的token，因为每次请求都要重新登录

        String token = getRequestToken(req);//从请求中获取token
        if (StrUtil.isBlank(token)) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//设置状态码
            resp.getWriter().print("无效的令牌");//输出错误信息
            return false;
        }
        //-safe-
        try{//捕获异常，因为token可能过期
            jwtUtil.verifierToken(token);//验证token
        }catch (TokenExpiredException e){//捕获异常，因为token可能过期
           if(redisTemplate.hasKey(token)) {//判断token是否在redis中
               //有的话，说明客户端保存到token已经过期，但是服务端的没过期，则要进行令牌的刷新，生成新的令牌
               redisTemplate.delete(token);//删除token
              int userId = jwtUtil.getUserId(token);//获取userId(过期的)
               token = jwtUtil.createToken(userId);//生成新的token，根据老令牌获得的userId
               redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);//保存数据（key，value，过期时间,单位）
               //新生成的令牌不光存到reids,还有给threadLocalToken
               threadLocalToken.setToken(token);//把token存到线程中
           }
           else{//客户端的令牌过期，服务器缓存的令牌也没有，重新登录
               resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//设置状态码
               resp.getWriter().print("令牌已过期");//输出错误信息
               return false;
           }
        }catch (JWTDecodeException e){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//设置状态码
            resp.getWriter().print("无效的令牌");//输出错误信息
            return false;
        }
        boolean bool = executeLogin(request,response);//执行登录,间接调用realm类的doGetAuthenticationInfo方法
        return bool;//如果是false，说明认证与授权失败
    }

    @Override//登录，认证失败：返回一个错误消息
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) request;
        resp.setContentType("test/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));//允许跨域
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//设置状态码
        try {
            resp.getWriter().print(e.getMessage());//输出错误信息
        }catch (Exception ex){

        }
        return false;
    }

    //掌管拦截请求和返回响应 的方法
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        super.doFilterInternal(request, response, chain);
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;//强转
        String token = getRequestToken(req);//从请求中获取token
        if (StrUtil.isNotBlank(token)) {
            threadLocalToken.setToken(token);//把token存到线程中
            return new OAuth2Token(token);//把token封装成AuthenticationToken对象
        }
        return null;
    }

    @Override
    //判断哪一种请求可以被shiro框架处理
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        if(req.getMethod().equals(RequestMethod.OPTIONS.name())){//判断是不是options请求
            return true;//不会由shiro框架处理
        }
        return false;
    }




}
